import React from 'react';
import {App, Button, Card, DatePicker, Form, Input, InputNumber} from "antd";
import {Link, useNavigate} from "react-router-dom";
import {ReimburseType} from "type/ReimburseType";
import LogFactory from "log/LogFactory";
import TextArea from "antd/es/input/TextArea";
import locale from "antd/es/date-picker/locale/zh_CN";
import dayjs from "dayjs";
import {useAppDispatch} from "../../../redux/hook";
import {fetchAddReimburse} from "../../../redux/reducer/async/reimburseAsyncAction";

const log = LogFactory.getLog("ReimburseAddComponent");
const ReimburseAddComponent = () => {

    const [loading, setLoading] = React.useState(false);
    const [form] = Form.useForm<ReimburseType>();
    const {message} = App.useApp();
    const navigate = useNavigate();
    const dispatch = useAppDispatch();

    const onFinish = async (values: ReimburseType) => {
        setLoading(true) ;
        values.createDate = values.createDate.format("YYYY-MM-DD");
        let res = await dispatch(fetchAddReimburse(values)).unwrap().then(res => res);
        if (res.success) {
            // log.debug("添加数据成功");
            message.success("添加数据成功");
            navigate("..", {replace: true});
        } else {
            log.debug("添加数据失败");
            message.error("添加数据失败");
        }
        setLoading(false) ;
    };
    const initialValues: Partial<ReimburseType> = {
        totalAmount: 0.00,
        itemCount: 0,
        createDate: dayjs(new Date()),
    };

    return (
        <Card
            title="添加报销单"
            extra={<Link to="..">报销单列表</Link>}
        >
            <Form<ReimburseType>
                form={form}
                layout={"horizontal"}
                labelCol={{span: 6}}
                wrapperCol={{span: 12}}
                initialValues={initialValues}
                onFinish={onFinish}
            >
                <Form.Item<ReimburseType> label="报销总金额" name={"totalAmount"}>
                    <InputNumber min={0.00} precision={2} addonBefore={"¥"}/>
                </Form.Item>
                <Form.Item<ReimburseType> label="报销总条目" name={"itemCount"}>
                    <InputNumber min={0} addonAfter={"条"}/>
                </Form.Item>
                <Form.Item<ReimburseType> label="报销单说明" name={"explain"}>
                    <Input/>
                </Form.Item>
                <Form.Item<ReimburseType> label="创建日期" name={"createDate"}>
                    <DatePicker locale={locale} format={"YYYY-MM-DD"}/>
                </Form.Item>

                <Form.Item<ReimburseType> label="备注信息" name={"remark"}>
                    <TextArea rows={3}/>
                </Form.Item>
                <Form.Item wrapperCol={{offset: 8, span: 16}}>
                    <Button loading={loading} type="primary" htmlType="submit">添加</Button>
                </Form.Item>
            </Form>
        </Card>
    );
};

export default ReimburseAddComponent;